package com.xcity.game.rank.impl;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.Lock;

import com.xcity.db.entity.Player;
import com.xcity.db.entity.Ranking;
import com.xcity.game.common.GameStaticConfig;
import com.xcity.game.event.GameEvents;
import com.xcity.game.rank.BaseRankingList;

import naga.x.App;
import naga.x.event.Event;

public class ArenaOfflineRankingList extends BaseRankingList {

	public ArenaOfflineRankingList(int type, int capacity, Comparator<Ranking> comparator) {
		super(type, capacity, comparator);
	}

	@Override
	public int[] getEventTypes() {
		return new int[] { GameEvents.EVENT_PLAYER_LEVEL_UP };
	}

	@Override
	public void handleEvent(Event event) {
		List<Ranking> list = getEntries();
		Player player = event.getParameter();
		if (list.size() < getCapacity() && player.getLevel() >= GameStaticConfig.arenaOpenLvl) {
			if (findEntry(player) == null) {
				Ranking ranking = new Ranking(player.getId(), getType(), -list.size());
				add(ranking);
				App.getApp().getEventManager().addEvent(GameEvents.EVENT_RANKING_UPPED, player, ranking.getIndex() + 1, type);
			}
		}
	}

	@Override
	public boolean swap(Player player1, Player player2) {
		final Lock lock = this.lock;
		lock.lock();
		try {
			Ranking entry1 = findEntry(player1);
			if (entry1 == null) {
				entry1 = new Ranking(player1, type, -entries.size());
				if (entries.size() < capacity) {
					add(entry1);
				}
			}
			
			Ranking entry2 = findEntry(player2);
			if (entry2 == null) {
				entry2 = new Ranking(player2, type, -entries.size());
				if (entries.size() < capacity) {
					add(entry2);
				}
			}
			
			if (entry1.getIndex() >= 0 && entry1.getIndex() <= entry2.getIndex()) {
				// player1排名高于player2不交换
				return false;
			}
			
			entryLookup.remove(entry1.getPlayerId());
			entryLookup.remove(entry2.getPlayerId());
			
			entry1.setPlayerId(player2.getId());
			entry2.setPlayerId(player1.getId());
			if (entry1.getIndex() >= 0) {
				entryLookup.put(entry1.getPlayerId(), entry1);
			}
			if (entry2.getIndex() >= 0) {
				entryLookup.put(entry2.getPlayerId(), entry2);
			}
			App.getApp().getEventManager().addEvent(GameEvents.EVENT_RANKING_UPPED, player1, entry2.getIndex() + 1, type);
			return true;
		} finally {
			lock.unlock();
		}
	}

}
